using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebPartPages;
using jQuery.ScriptManager;

namespace SPImageCarousel
{
    public class SPImageCarousel : Microsoft.SharePoint.WebPartPages.WebPart
    {
        protected string imageLibraryName = string.Empty;

        protected Literal placeHolderLiteral = new Literal();
        protected Literal jsLiteral = new Literal();
        jQueryManager jqueryManager = null;

        protected override void OnInit(EventArgs e)
        {
            
            jqueryManager = jQueryManager.GetCurrent(Page);
            if (jqueryManager == null)
            {
                jqueryManager = new jQueryManager();
                Page.Controls.Add(jqueryManager);
            }
            Page.ClientScript.RegisterClientScriptInclude("JCarousel", Page.ClientScript.GetWebResourceUrl(this.GetType(), "JQueryWebParts.js.jquery.jcarousel.pack.js"));
            base.OnLoad(e);
        }

        
        protected override void CreateChildControls()
        {
            //setup the page for the carousel
            
            this.Controls.Add(placeHolderLiteral);
                
            this.Controls.Add(jsLiteral);

            base.CreateChildControls();
        }

        protected override void OnPreRender(EventArgs e)
        {
            StringBuilder jsArrayDef = new StringBuilder("var carouselItems" + this.ID + " = [");
            jsArrayDef.Append(CreateJSArray());
            jsArrayDef.Append("];");

            StringBuilder jsBindingMethod = new StringBuilder();
            jsBindingMethod.Append(@"function carousel_itemLoadCallback" + this.ID + "(carousel, state){for (var i = carousel.first; i <= carousel.last; i++) {if (carousel.has(i)) {continue;}if (i > carouselItems"+ this.ID +".length) {break;}carousel.add(i, getItemHTML"+ this.ID +"(carouselItems"+ this.ID +"[i-1]));}}");
            jsBindingMethod.Append(Environment.NewLine);
            jsBindingMethod.Append("function getItemHTML"+ this.ID +"(item){return '<img src=\"' + item.url + '\" width=\"75\" height=\"75\" alt=\"' + item.url + '\" />';};");

            placeHolderLiteral.Text = "<ul id=\"carousel\" class=\"jcarousel-skin-ie7\"></ul>";
            
            jqueryManager.RegisterScript(jsArrayDef.ToString());
            jqueryManager.RegisterScript(jsBindingMethod.ToString());
            jqueryManager.ReadyFunctions.Add(new StartFunction("jQuery('#carousel').jcarousel({size: carouselItems" + this.ID + ".length,itemLoadCallback: {onBeforeAnimation: carousel_itemLoadCallback" + this.ID + "}});"));

            base.OnPreRender(e);
        }
        

        protected string CreateJSArray()
        {
            try
            {
                StringBuilder jsArray = new StringBuilder();

                //grab the items from the list
                SPSite site = SPContext.GetContext(HttpContext.Current).Site;
                SPWeb web = site.OpenWeb();

                foreach (SPList list in web.Lists)
                {
                    if (list.BaseTemplate == SPListTemplateType.PictureLibrary && list.Title.Equals(imageLibraryName, StringComparison.InvariantCultureIgnoreCase))
                    {
                        //grab the images from this list
                        jsArray.Append(ProcessList(list));
                    }
                }

                //make sure the array is formed correctly

                string createdArray = jsArray.ToString();

                if (createdArray.EndsWith(","))
                {
                    createdArray = jsArray.Remove(jsArray.Length - 1, 1).ToString();
                }

                return createdArray;

            }
            catch (Exception) { }

            return string.Empty;
        }

        
        protected string ProcessList(SPList list)
        {
            StringBuilder sb = new StringBuilder();

            SPListItemCollection listItems = list.Items;

            foreach (SPListItem listItem in listItems)
            {
                SPListItem item = list.GetItemById(listItem.ID);
                sb.Append("{url: \"/");
                sb.Append(item.Url);
                sb.Append("\", title: \"");
                sb.Append(item.Title);
                sb.Append("\"},");
            }

            return sb.ToString();
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolparts = new ToolPart[2];
            toolparts[0] = new WebPartToolPart();
            toolparts[1] = new PicListToolPart();
            return toolparts;
        }

       

        public string ImageLibraryName
        {
            get { return imageLibraryName; }
            set { imageLibraryName = value; }
        }
        
        
	
    }
}
